package com.zzyl.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.AlertDataHandleDto;
import com.zzyl.dto.AlertDataPageQueryDto;
import com.zzyl.entity.AlertData;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.AlertDataVo;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Description AlertDataServiceImpl
 * @Author duzhengxu
 * @Date 2024-09-15
 */
@Service
@Slf4j
public class AlertDataServiceImpl implements AlertDataService {

    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 分页查询报警数据
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponse<AlertDataVo> page(AlertDataPageQueryDto dto) {
        //获取当前登录的用户id以筛选发送到当前账号的通知
        String subject = UserThreadLocal.getSubject();
        UserVo userVo = JSONUtil.toBean(subject, UserVo.class);

        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        LocalDateTime begin = null;
        LocalDateTime end = null;
        if(dto.getStartTime()!=null && dto.getEndTime()!=null) {
            begin = LocalDateTimeUtil.of(dto.getStartTime());
            end = LocalDateTimeUtil.of(dto.getEndTime());
        }
        String deviceName = dto.getDeviceName();
        Long id = dto.getId();
        Integer status = dto.getStatus();
        Page<AlertDataVo> page = alertDataMapper.page(userVo.getId(),deviceName,id,status,begin,end);
        return PageResponse.of(page,AlertDataVo.class);
    }

    /**
     * 处理设备报警数据
     *
     * @param id
     * @return
     */
    @Autowired
    private UserMapper userMapper;
    @Override
    //采用iotId和status串联不同用户的警报数据*********************************(status = 0'未处理')
    public void handleAlertData(Long id, AlertDataHandleDto alertDataHandleDto) {
        AlertData alertData = alertDataMapper.selectByPrimaryKey(id);
        String iotId = alertData.getIotId();

        //准备数据
        String subject = UserThreadLocal.getSubject();
        UserVo userVo = JSONUtil.toBean(subject, UserVo.class);
        Long processorId = userVo.getId();
        String processorName = userMapper.findUsernameById(processorId);
        String processingResult = alertDataHandleDto.getProcessingResult();
        LocalDateTime processingTime = alertDataHandleDto.getProcessingTime();

        alertDataMapper.handleAlertData(processorId,processorName,processingResult,processingTime,iotId);
    }
}
